/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AppMainWindow.java
 * Face of Evil!
 * Created on Oct 28, 2011, 10:34:07 AM
 */
package snmpapplication.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import snmpapplication.Main;
import snmpapplication.beans.ManagedDevice;
import snmpapplication.log.Severity;
import snmpapplication.observer.DeviceListener;
import snmpapplication.utils.DevicesManager;
import snmpapplication.utils.ListRenderer;
import snmpapplication.utils.ReachabilityService;

/**
 *
 * @author APetcu
 */
public class AppMainWindow extends javax.swing.JFrame implements DeviceListener, Runnable {

    /** Creates new form AppMainWindow */
    public AppMainWindow() {

        initComponents();

        initModel();

        initPopupMenu();

        setLocationRelativeTo(null);

        new ReachabilityService().start();
        Main.log.log(new Severity(Severity.SEV_INFO), "Started the Reachability Service");

        setVisible(true);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPopupMenu1 = new javax.swing.JPopupMenu();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JPopupMenu.Separator();
        jMenuItem3 = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        jMenuItem4 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem5 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("SnmpApplication");
        setBackground(new java.awt.Color(204, 255, 255));
        setMinimumSize(new java.awt.Dimension(60, 250));
        setResizable(false);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel1.setText("List of managed devices");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addComponent(jLabel1)
                .addContainerGap(158, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addContainerGap())
        );

        getContentPane().add(jPanel1, java.awt.BorderLayout.PAGE_START);

        jList1.setModel(model);
        jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jList1.setCellRenderer(new ListRenderer());
        jList1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jList1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jList1);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 307, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(11, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 325, Short.MAX_VALUE)
                .addContainerGap())
        );

        getContentPane().add(jPanel2, java.awt.BorderLayout.CENTER);

        jMenu1.setText("File");
        jMenu1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenu1ActionPerformed(evt);
            }
        });

        jMenuItem1.setText("Add device");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuItem2.setText("Delete device");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem2);
        jMenu1.add(jSeparator2);

        jMenuItem3.setText("Properties");
        jMenu1.add(jMenuItem3);
        jMenu1.add(jSeparator1);

        jMenuItem4.setText("Exit");
        jMenuItem4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem4ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem4);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Help");

        jMenuItem5.setText("Help");
        jMenuItem5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem5ActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItem5);

        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jMenu1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jMenu1ActionPerformed

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        // TODO add your handling code here:
        addDevice();
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed
        // TODO add your handling code here:
        int r = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit?", "Exit", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE);

        if (r == 0) {
            Main.log.log(new Severity(Severity.SEV_INFO), "Exit with code 0");
            System.exit(0);
        }

    }//GEN-LAST:event_jMenuItem4ActionPerformed

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        // TODO add your handling code here:
        deleteDevice();
    }//GEN-LAST:event_jMenuItem2ActionPerformed

    private void jList1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList1MouseClicked
        // TODO add your handling code here:
        if (evt.getClickCount() == 2) {
            AppDeviceDetailsWindow adw = new AppDeviceDetailsWindow((ManagedDevice) jList1.getSelectedValue());
            adw.setVisible(true);
        }
    }//GEN-LAST:event_jList1MouseClicked

    private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem5ActionPerformed
        // TODO add your handling code here:
        AppHelpWindow ah = new AppHelpWindow();
        ah.setVisible(true);
    }//GEN-LAST:event_jMenuItem5ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JList jList1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JMenuItem jMenuItem4;
    private javax.swing.JMenuItem jMenuItem5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JPopupMenu.Separator jSeparator2;
    // End of variables declaration//GEN-END:variables
    private DefaultListModel model = new DefaultListModel();
    private JPopupMenu jPopupMenu2;
    private JMenuItem jmi1;
    private JMenuItem jmi2;
    private JMenuItem jmi3;
    private JMenuItem jmi4;
    public static ReachabilityService rs;

    private synchronized void initModel() {
        model.clear();

        for (ManagedDevice st : DevicesManager.deviceList) {
            model.addElement(st);
        }
    }

    private void initPopupMenu() {

        jPopupMenu1 = new JPopupMenu();
        jPopupMenu2 = new JPopupMenu();

        jmi1 = new JMenuItem("Add device");
        jmi4 = new JMenuItem("Add device");
        jPopupMenu1.add(jmi1);
        jPopupMenu2.add(jmi4);

        jmi2 = new JMenuItem("Details");
        jPopupMenu1.add(jmi2);

        jmi3 = new JMenuItem("Delete");
        jPopupMenu1.add(jmi3);

        jList1.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseReleased(MouseEvent Me) {

                if (jList1.getSelectedValue() != null) {
                    if (Me.isPopupTrigger()) {
                        jPopupMenu1.show(Me.getComponent(), Me.getX(), Me.getY());
                    }
                } else {
                    if (Me.isPopupTrigger()) {
                        jPopupMenu2.show(Me.getComponent(), Me.getX(), Me.getY());
                    }
                }
            }
        });

        jmi1.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                addDevice();
            }
        });

        jmi4.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                addDevice();
            }
        });

        jmi2.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                AppDeviceDetailsWindow adw = new AppDeviceDetailsWindow((ManagedDevice) jList1.getSelectedValue());
                adw.setVisible(true);
            }
        });

        jmi3.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                deleteDevice();
            }
        });

    }

    private void addDevice() {

        AppAddDevice aad = new AppAddDevice();
        aad.setLocationRelativeTo(null);
        aad.addDeviceListener(AppMainWindow.this);
        aad.setVisible(true);
    }

    @Override
    public void addedDevice() {
        try {
            DevicesManager.loadDevices();

            initModel();
            Main.log.log(new Severity(Severity.SEV_INFO), "Model initialized");

        } catch (Exception ex) {
            Main.log.log(new Severity(Severity.SEV_ERR), "Exception when adding device: " + ex.getMessage());
        }
    }

    private void deleteDevice() {

        try {
            AppMainWindow.rs.sleep(300);
            this.sleep(300);
        } catch (InterruptedException ex) {
            Logger.getLogger(AppAddDevice.class.getName()).log(Level.SEVERE, null, ex);
        }

        if (jList1.getSelectedValue() == null) {
            JOptionPane.showMessageDialog(null, "No selected object to delete!", "Error", JOptionPane.ERROR_MESSAGE);
            Main.log.log(new Severity(Severity.SEV_MED), "Try to delete a non-selected device");
            return;
        }

        int r = JOptionPane.showConfirmDialog(null, "Are you sure you want to delete this object?", "Confirm", JOptionPane.WARNING_MESSAGE);

        if (r == 0) {

            ManagedDevice md = (ManagedDevice) jList1.getSelectedValue();

            synchronized (DevicesManager.deviceList) {
                DevicesManager.deviceList.remove(md);
                DevicesManager.deleteDevice(md);
            }

            Main.log.log(new Severity(Severity.SEV_INFO), "Device deleted");

            initModel();

            Main.log.log(new Severity(Severity.SEV_INFO), "Model initialization finished");

        }

    }

    @Override
    public void run() {

        while (true) {
            try {
                Thread.sleep(4000);

                jList1.repaint();
            } catch (InterruptedException ex) {
                Main.log.log(new Severity(Severity.SEV_ERR), "Thread interrupted: " + ex.getMessage());
            }
        }
    }

    public static void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException ex) {
            Logger.getLogger(AppMainWindow.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}
